from logging import getLogger

from django.core.cache import cache
from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from django.views import View

from .models import Area

logger = getLogger('django')


def get_provinces_info():
    """
    获取省份信息
    :return:
    """
    # 查询缓存
    # print('查询缓存')
    provinces = cache.get('province_info')
    if provinces:
        return provinces
    # 查询数据库
    try:
        provinces_set = Area.objects.filter(area=None)
    except Exception as e:
        return JsonResponse({'code': 4102, 'errmsg': '数据库错误'},
                            json_dumps_params={"ensure_ascii": False})
    if not provinces_set:
        return JsonResponse({'code': 4103, 'errmsg': '数据库中没有省份信息'},
                            json_dumps_params={"ensure_ascii": False})
    if provinces_set.count() != 34:
        return JsonResponse({'code': 4104, 'errmsg': '省份信息总数不对'},
                            json_dumps_params={"ensure_ascii": False})
    """
    'data': [{'id': code, 'name': name}, ...]
    """
    provinces = []
    for i in provinces_set:
        provinces.append({'id': i.code, 'name': i.name})
    # 使用缓存，默认存进 redis 'default' 库
    # print('放进缓存')
    cache.set('province_info', provinces, 3600)
    return provinces


def get_subareas(area_id):
    """
    获取分区信息
    :param area_id: 区域id
    :return: 字典：区域信息和分区列表
    """
    # 查询缓存
  # print('查询缓存')
    data = cache.get('subareas_%s' % area_id)
    if data:
        return data
    # 查询数据库
  # print('查询数据库')
    try:
        area = Area.objects.get(code=area_id)
        # print(area)
        subarea_set = area.subarea.all()
        # print(subarea_set)
    except Area.DoesNotExist:
        return JsonResponse({'code': 4102, 'errmsg': '无效的区码'},
                            json_dumps_params={"ensure_ascii": False})
    except Exception as e:
        logger.error('区划联动 【异常】 %s' % e)
        return JsonResponse({'code': 4102, 'errmsg': '数据库错误'},
                            json_dumps_params={"ensure_ascii": False})
    if not subarea_set:
        return JsonResponse({'code': 4103, 'errmsg': '数据库中没有%s分区信息' % area},
                            json_dumps_params={"ensure_ascii": False})

    """
    'subs': [{'id': code, 'name': name}]
    """
    subs = []
    for i in subarea_set:
        subs.append({'id': i.code, 'name': i.name})
    data = {'id': area.code, 'name': area.name, 'subs': subs}
    # 放进缓存
    # print('放进缓存')
    cache.set('subareas_%s' % area_id, data, 3600)
    return data


class GetAreas(View):

    def get(self, request):

        area_id = request.GET.get("area_id")

        if not area_id:
            # 获取省份信息
            try:
                data = get_provinces_info()
            except Exception as e:
                return JsonResponse({'code': 4105, 'errmsg': '服务器出错'},
                                    json_dumps_params={"ensure_ascii": False})
        else:
            # 获取市区信息
            try:
                data = get_subareas(area_id)
            except Exception as e:
                return JsonResponse({'code': 4105, 'errmsg': '服务器出错'},
                                    json_dumps_params={"ensure_ascii": False})

        if isinstance(data, JsonResponse):
            return data

        # print(data)
        return JsonResponse({'code': 0, 'data': data, },
                            json_dumps_params={"ensure_ascii": False})
